﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Ext.Net;
using Sharp.DataTransferObject;
using Sharp.Infrastructure;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.Mvc;
using Sharp.ServiceContracts;
using PartialViewResult = Ext.Net.MVC.PartialViewResult;
using Task = System.Threading.Tasks.Task;

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    public class OAuthController : SharpController
    {
        //[Permission("快捷登录", 1,  "002006")]
        public ActionResult Index(string containerId)
        {
            IList<OAuthConfigDTO> configs;
            using (var proxy = new WebApiClientServiceProxy<IPlatformService>())
            {
                configs = proxy.Channel.GetOAuthConfigs();
            }
            var arrays = Enum.GetValues(typeof(OAuthConfigDTO.OAuthType));
            IList<OAuthConfigDTO> OAuths = new List<OAuthConfigDTO>();
            foreach (OAuthConfigDTO.OAuthType config in arrays)
            {
                if (config == OAuthConfigDTO.OAuthType.None)
                {
                    continue;
                }
                var data = configs.FirstOrDefault(x => x.Interface == config);
                if (data == null)
                {
                    data = new OAuthConfigDTO() {Interface = config, IsEnable = true};
                }
                data.Name = config.GetDescription();
                OAuths.Add(data);
            }
            return new PartialViewResult
            {
                Model = OAuths,
                ContainerId = containerId,
                RenderMode = RenderMode.AddTo
            };

        }


        public ActionResult Save(FormCollection collection)
        {
            List<OAuthConfigDTO> oauthData = collection["oauthData"].FromJson<List<OAuthConfigDTO>>();
            if (oauthData == null)
            {
                return this.JsonNet(new Result { Err = "oauthData 不能为空" });
            }
            using (var proxy = new WebApiClientServiceProxy<IPlatformService>())
            {
                foreach (var dto in oauthData)
                {
                    var res = proxy.Channel.SaveOAuthConfig(dto);
                    if (res.Err.Length > 0)
                    {
                        return this.JsonNet(res);
                    }
                }
            }
            Task.Run(() =>
            {
                Thread.Sleep(2000);
                HttpRuntime.Close();//重启程序
            });
            return this.JsonNet(new Result());
        }
    }
}